import 'package:flutter/material.dart';
import 'package:fenzi/global.dart';

class FormText extends StatefulWidget {
  FormText({
    Key key,
    @required this.maxLine,
    @required this.hintText,
    this.text,
    this.onSubmitted,
    this.onChanged,
    this.onTap,
    this.controller,
    this.textAlign = TextAlign.end,
    this.keyboardType = TextInputType.text,
  }) : super(key: key);

  final int maxLine;
  final String hintText;
  final onSubmitted;
  final onChanged;
  final onTap;
  final controller;
  final String text;
  final TextAlign textAlign;
  final TextInputType keyboardType;

  @override
  State<StatefulWidget> createState() => _FormTextState(text);
}

class _FormTextState extends State<FormText> {
  String text;
  _FormTextState(this.text);

  bool _obscureText = false;
  TextEditingController _textController = TextEditingController();

  @override
  void initState() {
    _textController.text = this.text;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double maxTextWidth = MediaQuery.of(context).size.width;
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: maxTextWidth,
      ),
      child: TextField(
        onTap: widget.onTap,
        controller: _textController,
        obscureText: _obscureText && widget.maxLine == 1,
        maxLines: widget.maxLine,
        textAlign: widget.textAlign,
        style: TextStyle(
          color: Global.fontColor,
          fontSize: 14,
        ),
        decoration: InputDecoration.collapsed(
          hintText: widget.hintText,
          hintStyle: TextStyle(
            color: Global.fontSecondColor.withOpacity(0.5),
            fontSize: 14,
          ),
        ),
        keyboardType: widget.keyboardType,
        onSubmitted: widget.onSubmitted,
        onChanged: (text) {
          this.text = text;
          if (widget.onChanged != null) widget.onChanged(text);
        },
      ),
    );
  }
}
